let
, const
, and var
in JavaScript
JavaScript provides three ways to declare variables: var
, let
, and const
. Each has its unique characteristics and use cases.
var
undefined
.Example:
function testVar() {
var x = 10;
if (true) {
var x = 20; // re-declaration allowed
console.log(x); // Output: 20
}
console.log(x); // Output: 20
}
testVar();
let
Example:
function testLet() {
let x = 10;
if (true) {
let x = 20; // different variable due to block scope
console.log(x); // Output: 20
}
console.log(x); // Output: 10
}
testLet();
const
let
).const
can be modified.Example:
function testConst() {
const x = 10;
console.log(x); // Output: 10
// x = 20; // Error: Assignment to constant variable
const obj = { name: "John" };
obj.name = "Jane"; // Allowed: object properties can be modified
console.log(obj.name); // Output: Jane
}
testConst();
Feature | var |
let |
const |
---|---|---|---|
Scope | Function/Global | Block | Block |
Hoisting | Hoisted and initialized with undefined |
Hoisted but not initialized | Hoisted but not initialized |
Re-declaration | Allowed | Not Allowed | Not Allowed |
Reassignment | Allowed | Allowed | Not Allowed |